package com.xzc.one.controller.Base;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.*;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * http请求
 *
 * @author xzcong
 * @create 2019-10-20 14:32
 **/
public class HttpKit {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpSession session;

    protected String getIP() {
        return request.getRemoteHost();
    }

    protected void printSession() {
        System.err.println(session.getId());
        Enumeration<?> enumeration = session.getAttributeNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement().toString();
            Object value = session.getAttribute(name);
            System.out.println(name + "<<<<<<=========================>>>>>>>" + value);
        }
    }

    protected void setCookie(String name, String value, int time) {
        Cookie cookie = new Cookie(name, value);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(time);//缓存时间
        response.addCookie(cookie);
    }

    protected String getCookie(String name) {
        if (request.getCookies() == null) return null;
        List<Cookie> cookies = Arrays.stream(request.getCookies()).filter(r -> r.getName().equals(name)).collect(Collectors.toList());
        return cookies.size() > 0 ? cookies.get(0).getValue() : null;
    }
}
